import { ref, reactive } from 'vue'
import { logout, updatePassword, addUser } from '~/api/manager'
import { showModel, toast } from '~/composables/util'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
export function useRepassword() {
  const router = useRouter()
  const store = useStore()
  const formDrawerRef = ref(null)
  const formRef = ref(null)
  // do not use same name with ref
  const form = reactive({
    oldpassword: '',
    password: '',
    repassword: ''
  })
  const onSubmit = () => {
    // console.log('submit!')
    formRef.value.validate((valid) => {
      if (!valid) {
        return false
      }
      console.log('验证通过')
      formDrawerRef.value.showLoading()
      updatePassword(form)
        .then((res) => {
          if (res.code == 0){
            toast('修改密码成功,请重新登录')
            store.dispatch('logout')
            // 跳转回登录页
            router.push('/login')
          }
          else{
            toast(res.message)
            store.dispatch('logout', 'error')
            // 跳转回登录页
            router.push('/login')
          }
        })
        .finally(() => {
          formDrawerRef.value.hideLoading()
        })
    })
  }

  const rules = {
    oldpassword: [
      {
        required: true,
        message: '旧密码不能为空',
        trigger: 'blur'
      }
    ],
    password: [
      {
        required: true,
        message: '新密码不能为空',
        trigger: 'blur'
      }
    ],
    repassword: [
      {
        required: true,
        message: '确认密码不能为空',
        trigger: 'blur'
      }
    ]
  }

  const openRepasswordForm = () => formDrawerRef.value.open()

  return {
    formDrawerRef,
    formRef,
    form,
    onSubmit,
    rules,
    openRepasswordForm
  }
}

export function useLogout() {
  const router = useRouter()
  const store = useStore()

  function hadleLogout() {
    showModel('是否退出登录？').then((res) => {
      console.log('点击了确定 退出登录')
      logout().finally((res) => {
        store.dispatch('logout')
        // 跳转回登录页
        router.push('/login')

        // 提示
        toast('退出登录成功')
      })
    })
  }
  return {
    hadleLogout
  }
}

export function useRegister() {
  const router = useRouter()
  const formDrawerRef = ref(null)
  const formRef = ref(null)
  const loading = ref(false)

  const form = reactive({
    username: '',
    password: '',
    repassword: '',
    email: ''
  })

  const rules = {
    username: [
      { required: true, message: '用户名不能为空', trigger: 'blur' },
      { 
        validator: (rule, value, callback) => {
          if (value.length < 3 || value.length > 16) {
            callback(new Error('用户名长度应在 3 到 16 个字符之间'))
          } else if (!/^[a-zA-Z0-9_]+$/.test(value)) {
            callback(new Error('用户名只能包含字母、数字和下划线'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
       }
    ],
    password: [
      { required: true, message: '密码不能为空', trigger: 'blur' },
      { min: 6, max: 20, message: '密码长度应在 6 到 20 个字符之间', trigger: 'blur' }
    ],
    repassword: [
      { required: true, message: '确认密码不能为空', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value !== form.password) {
            callback(new Error('两次输入的密码不一致'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ],
    email: [
      { required: true, message: '邮箱不能为空', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ]
  }

  const onSubmit = () => {
    formRef.value.validate((valid) => {
      if (!valid) {
        return false
      }
      loading.value = true
      addUser(form)
        .then((res) => {
          if (res.code === 0) {
            toast('注册成功，请登录')
            formDrawerRef.value.close()
            router.push('/login')

          } else {
            toast(res.message, 'error')
          }
        })
        .finally(() => {
          loading.value = false
        })
    })
  }

  const openRegisterForm = () => formDrawerRef.value.open()

  return {
    formDrawerRef,
    formRef,
    form,
    onSubmit,
    rules,
    openRegisterForm,
    loading
  }
}


